package com.lt.flashcard.view;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.ContentCategory;
import com.lt.flashcard.model.service.ContentService;
import com.lt.flashcard.model.service.Repository;

public class AdminContentCategoryVm {
	
	private List<ContentCategory> categories;
	private ContentCategory category = null; //Store current top category
	
	@Init
	public void init() {
		Utility.adminLoginOrAccessDenied(false);
		loadCategories();
	}

	public List<ContentCategory> getCategories() {
		return categories;
	}

	public void setCategories(List<ContentCategory> categories) {
		this.categories = categories;
	}
	
	private void loadCategories() {
		ContentService srv = Repository.getInstance().getContentService();
		if(getCategory() == null) {
			setCategories(srv.getAllCategories());
		}
		else {
			categories = getCategory().getChild();
		}
	}
	
	@NotifyChange("categories")
	@Command
	public void addnew(@BindingParam("name") String name) {
		if(StringUtils.isNotBlank(name)) {
			ContentService srv = Repository.getInstance().getContentService();
			ContentCategory cat = new ContentCategory();
			cat.setName(name);
			if(category != null) {
				cat.setParent(category);
				srv.saveCategory(cat);
				category.getChild().add(cat);
				srv.saveCategory(category);
			}
			else {
				srv.saveCategory(cat);
			}
			loadCategories();
		}
	}
	
	@NotifyChange("categories")
	@Command
	public void delete(@BindingParam("id") String id) {
		if(StringUtils.isNotBlank(id)) {
			ContentService srv = Repository.getInstance().getContentService();
			srv.deleteCategory(srv.getCategory(id));
			loadCategories();
		}
	}
	
	@NotifyChange({"categories", "category"})
	@Command
	public void detail(@BindingParam("id") String id) {
		if(StringUtils.isNotBlank(id)) {
			ContentService srv = Repository.getInstance().getContentService();
			setCategory(srv.getCategory(id));
			loadCategories();
		}
	}
	
	@NotifyChange({"categories", "category"})
	@Command
	public void up() {
		if(getCategory() != null) {
			setCategory(getCategory().getParent());
			loadCategories();
		}
	}

	public ContentCategory getCategory() {
		return category;
	}

	public void setCategory(ContentCategory category) {
		this.category = category;
	}
}
